fn to_decimal(num_str: &str, base: u32) -> Result<u32, String> {
    let mut result = 0;
    for (i, c) in num_str.chars().rev().enumerate() {
        let digit = match c.to_digit(36) {
            Some(d) => d,
            None => return Err(format!("Invalid character: {}", c)),
        };
        if digit >= base {
            return Err(format!("Digit {} is not valid in base {}", digit, base));
        }
        result += digit * base.pow(i as u32);
    }
    Ok(result)
}

fn from_decimal(mut num: u32, base: u32) -> String {
    if base < 2 || base > 16 {
        return "Invalid base".to_string();
    }
    if num == 0 {
        return "0".to_string();
    }
    let digits = "0123456789abcdef";
    let mut result = String::new();
    while num > 0 {
        let remainder = num % base;
        result.push(digits.chars().nth(remainder as usize).unwrap());
        num /= base;
    }
    result.chars().rev().collect()
}

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    let open_paren = num_str.find('(');
    let close_paren = num_str.rfind(')');

    let open_paren = open_paren.unwrap();
    let close_paren = close_paren.unwrap();

    let input_num = &num_str[0..open_paren];
    let from_base_str = &num_str[open_paren + 1..close_paren];
    let from_base = from_base_str.parse::<u32>().unwrap();

    let decimal = to_decimal(input_num, from_base).unwrap();
    from_decimal(decimal, to_base)
}
